package com.wulian.service.impl;


import com.wulian.entities.Record;
import com.wulian.service.FabricService;
import com.wulian.utils.FabricUtil;
import org.hyperledger.fabric.gateway.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeoutException;

/**
 * @author xf
 * @date 2021/3/23 下午 1:01
 * @Description
 */
@Service
public class FabricServiceImpl implements FabricService {

    public final static String HOSPITAL_NAME = "娄底市中心医院";


    @Override
    public String getRecordById(Long id) throws IOException, CertificateException, InvalidKeyException, ContractException, TimeoutException, InterruptedException {

        //获取合约对象
        Contract contract = FabricUtil.getContract();

        byte[] result = contract.evaluateTransaction("GetRecordById",id.toString());

        String json = new String(result, StandardCharsets.UTF_8);

        System.out.println(json);
        return null;
    }

    @Override
    public Boolean addRecordToFabric(Record record) throws CertificateException, InvalidKeyException, IOException, InterruptedException, TimeoutException, ContractException {
        Contract contract = FabricUtil.getContract();

        System.out.println(record);

        byte[] result = contract.createTransaction("CreateRecord")
                .submit(record.getRecord_id().toString(), record.getPatient().getPatient_name(), record.getRecord_symptom(), record.getRecord_case_history(), record.getRecord_check(), record.getDoctor().getDoctor_name(), record.getDepartment().getDepartment_name(), HOSPITAL_NAME, record.getRecord_time().toLocaleString());

        String json = new String(result, StandardCharsets.UTF_8);

        System.out.println(json);

        if (json!=null){
            return true;
        }

        return false;
    }

}
